﻿using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Fatec.ControleEstoque.Interface
{

    public partial class ListViewPager : System.Web.UI.UserControl
    {
        protected void TemplatePagerField_OnPagerCommand(object sender, DataPagerCommandEventArgs e)
        {
            int newIndex;
            int lastPageNumber;
            int pageSize = Convert.ToInt32(((DropDownList)e.Item.FindControl("DropDownListPageSize")).SelectedValue); //e.Item.Pager.PageSize;
            int rowCount = e.TotalRowCount;

            switch (e.CommandName)
            {
                case "Next":
                    newIndex = e.Item.Pager.StartRowIndex + e.Item.Pager.PageSize;
                    if (newIndex <= e.TotalRowCount)
                        e.NewStartRowIndex = newIndex;
                    break;
                case "Previous":
                    if (e.Item.Pager.StartRowIndex != 0)
                        e.NewStartRowIndex = e.Item.Pager.StartRowIndex - pageSize;
                    break;
                case "First":
                    e.NewStartRowIndex = 0;
                    break;
                case "Last":
                    // Integer division
                    lastPageNumber = e.TotalRowCount / pageSize;
                    if ((rowCount % pageSize) == 0)
                        lastPageNumber -= 1;
                    e.NewStartRowIndex = lastPageNumber * pageSize;
                    break;
                case "Jump":
                    TextBox txtNewPageNumber = (TextBox)e.Item.FindControl("textNewPageNumber");
                    int newPageNumber = Int32.Parse(txtNewPageNumber.Text);

                    e.NewStartRowIndex = (newPageNumber - 1) * pageSize;
                    if (e.NewStartRowIndex > rowCount)
                    {
                        // Integer division
                        lastPageNumber = rowCount / pageSize;
                        if ((rowCount % pageSize) == 0)
                        {
                            lastPageNumber -= 1;
                        }
                        e.NewStartRowIndex = lastPageNumber * pageSize;
                    }
                    break;
            }
            e.NewMaximumRows = e.Item.Pager.MaximumRows;
        }

        protected void NewPageNumber_Changed(object sender, EventArgs e)
        {
            LinkButton btnJump = (LinkButton)((TextBox)sender).Parent.FindControl("buttonJump");
            ((IPostBackEventHandler)btnJump).RaisePostBackEvent(null);
        }

        protected void DropDownListPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList dropdownlistpagersize = (DropDownList)sender;
            DataPager1.PageSize = Convert.ToInt32(dropdownlistpagersize.SelectedValue);
        }
    }
}